package com.ruolin.micro.gateway.server.filter;

import com.ruolin.micro.gateway.server.servlet.bean.RouterBeanDefinition;
import com.ruolin.micro.gateway.server.route.RouteDefinitionLocator;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.List;

//@Component
//@WebFilter(filterName = "gatewayFilter", urlPatterns = "/d/*")
public class RouterFilter extends GatewayFilter{
    @Autowired
    private RouteDefinitionLocator routeDefinitionLocator;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest) {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            String pathInfo = request.getPathInfo();
            List<RouterBeanDefinition> routers = routeDefinitionLocator.getRouteDefinitions();
            boolean match = routers.stream().anyMatch(r -> r.getPath().startsWith(pathInfo));
            if (match) {
                throw new RemoteException("router is not match, path::::"+ pathInfo);
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    int getIndex() {
        return -1;
    }
}
